<template>
	<view class="patrol-inspection">
		<view class="box">
			<view class="title">设备序列号：{{ serialNumber }}</view>
			<view class="form-box">
				<view class="border-top"></view>
				<template v-for="(i, j) of equipmemtOptions" :key="j">
					<view class="label">{{ i.name }}</view>
					<radio-group @change="onRadioChange($event, i)" class="radio-group">
						<label class="radio-label flex align-center" v-for="(radio, index) in i.radioOptions" :key="index">
							<radio :value="index" :checked="i.checked === index" style="transform: scale(0.7)" />
							{{ radio }}
						</label>
					</radio-group>
				</template>
				<view class="label">设备巡检详情：</view>
				<view class="form-textarea">
					<uni-easyinput v-model="formFields.device_content" type="textarea" :input-border="false" class="textarea-box" placeholder="请输入设备巡检详情" />
					<view class="grid-box">
						<view v-for="(img, index) in formFields.device_imgs" :key="img" class="grid-item">
							<image class="cover-image" :src="img" mode="aspectFill" @click="previewImage(img)" />
							<text class="iconfont icon-close" @click="handleDeleteImg(index, 'device_imgs')"></text>
						</view>
						<view
							v-if="formFields.device_imgs.length < 9"
							class="grid-item upload-box flex align-center justify-center"
							@click="uploadImgsHandler('device_imgs')"
						></view>
					</view>
				</view>
			</view>
		</view>
		<view class="box" v-if="!!chassisNumber">
			<view class="title chassis_num">
				机箱序列号：{{ chassisNumber }}
				<view class="chassis_num_del" @click.stop="delChassis"><uni-icons type="trash" size="20"></uni-icons></view>
			</view>
			<view class="form-box">
				<view class="border-top"></view>
				<template v-for="(i, j) of chassisOptions" :key="j">
					<view class="label">{{ i.name }}</view>
					<radio-group @change="onRadioChange($event, i)" class="radio-group">
						<label class="radio-label flex align-center" v-for="(radio, index) in i.radioOptions" :key="index">
							<radio :value="index" :checked="i.checked === index" style="transform: scale(0.7)" />
							{{ radio }}
						</label>
					</radio-group>
				</template>
				<view class="label">机箱巡检详情：</view>
				<view class="form-textarea">
					<uni-easyinput v-model="formFields.cha_content" type="textarea" :input-border="false" class="textarea-box" placeholder="请输入机箱巡检详情" />
					<view class="grid-box">
						<view v-for="(img, index) in formFields.cha_imgs" :key="img" class="grid-item">
							<image class="cover-image" :src="img" mode="aspectFill" @click="previewImage(img)" />
							<text class="iconfont icon-close" @click="handleDeleteImg(index, 'cha_imgs')"></text>
						</view>
						<view v-if="formFields.cha_imgs.length < 9" class="grid-item upload-box flex align-center justify-center" @click="uploadImgsHandler('cha_imgs')"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="box" v-else @click="scanCodeInfo">
			<button class="scanCode">
				绑定机箱
				<uni-icons type="scan" size="20"></uni-icons>
			</button>
		</view>
		<button class="btn-primary btn-submit" @click="handleSubmits">提交</button>
		<up-modal :show="showPwd" showCancelButton @confirm="submitValPwd" @cancel="showPwd = false">
			<view class="slot-content">
				<up-input placeholder="请输入密码" border="surround" type="password" v-model="submitPwd"></up-input>
			</view>
		</up-modal>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { equipmemtOptions, chassisOptions } from './use';
import { previewImage, uploadFile } from '@/utils';
import { useUserStore } from '@/store/user';
import { postDevicePatrol, fetchDeviceInfo,valDevicePwd } from '@/api';
import { getURLQuery } from '@/utils';

const userStore = useUserStore();
const formFields = ref({
	device_content: '',
	cha_content: '',
	device_imgs: [],
	cha_imgs: []
});

const showPwd = ref(false);
const submitPwd = ref('');
const serialNumber = ref('');
const chassisNumber = ref('');
const oldChassisNumber = ref('');
const chassisConfig = ref([]);
onLoad((e) => {
	serialNumber.value = e?.serialNum;
	fetchDeviceInfo(e?.serialNum).then((res) => {
		if (res.cha_serial_no) {
			chassisNumber.value = res.cha_serial_no;
			oldChassisNumber.value = res.cha_serial_no;
		}
		chassisConfig.value = res.cha_config;
	});
});
const submitValPwd = () => {
	if (!submitPwd.value) {
		uni.$u.toast('请输入密码后提交');
		return false;
	}
	valDevicePwd({
		pwd:submitPwd.value
	}).then(res=>{
		handleSubmit()
		showPwd.value = false
	})
};
const keyMap = {
	'01': 'product_identification',
	11: 'production_date',
	17: 'expiry_date',
	21: 'host_serial_no',
	91: 'other'
};
function scanCodeInfo() {
	uni.scanCode({
		success(res) {
			const { query: querys = '' } = getURLQuery(res.result);
			if (!querys)
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			const params = querys.split('(');
			const temp = {};
			for (const param of params) {
				const splitStr = param.split(')');
				const key = splitStr[0];
				if (key in keyMap) temp[keyMap[key]] = splitStr[1];
			}
			console.log(temp);
			if (!temp.host_serial_no)
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			if (!temp.other) {
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			}
			if (chassisConfig.value.indexOf(temp.other) == -1) {
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			} else {
				chassisNumber.value = temp.host_serial_no;
			}
		}
	});
}
function delChassis() {
	uni.showModal({
		title: '确定删除机箱吗',
		showCancel: true,
		confirmText: '删除',
		cancelText: '取消',
		success(btn) {
			if (btn.confirm) {
				chassisNumber.value = '';
			}
		}
	});
}
function handleSubmits() {
	const showMsg = (title) => uni.showToast({ title, icon: 'none' });
	if (!formFields.value.device_content) return showMsg('请输入设备描述');
	if (!formFields.value.device_imgs.length) return showMsg('请上传设备描述图片');
	if (!!chassisNumber.value && !formFields.value.cha_content) return showMsg('请输入机箱描述');
	if (!!chassisNumber.value && !formFields.value.cha_imgs.length) return showMsg('请上传机箱描述图片');
	if ((chassisNumber.value != oldChassisNumber.value) && oldChassisNumber.value) {
		console.log('验证码');
		showPwd.value = true;
	} else {
		handleSubmit();
	}
}
function handleSubmit() {
	const showMsg = (title) => uni.showToast({ title, icon: 'none' });
	if (!formFields.value.device_content) return showMsg('请输入设备描述');
	if (!formFields.value.device_imgs.length) return showMsg('请上传设备描述图片');
	if (!!chassisNumber.value && !formFields.value.cha_content) return showMsg('请输入机箱描述');
	if (!!chassisNumber.value && !formFields.value.cha_imgs.length) return showMsg('请上传机箱描述图片');

	const params = {
		...formFields.value,
		device_imgs: formFields.value.device_imgs.join('|'),
		cha_imgs: formFields.value.cha_imgs.join('|'),
		host_serial_no: serialNumber.value,
		user_id: userStore.userInfo.id
	};
	equipmemtOptions.map((i) => (params[i.key] = i.checked));
	if (!!chassisNumber.value) {
		chassisOptions.map((i) => (params[i.key] = i.checked));
		params['cha_serial_no'] = chassisNumber.value;
	}
	params['old_chassis_number'] = oldChassisNumber.value || ''
	uni.showModal({
		title: '温馨提示',
		content: '确认提交当前设备巡检信息吗？',
		confirmColor: '#377DFF',
		success(res) {
			if (res.confirm) {
				postDevicePatrol(params).then(() => {
					showMsg('已提交');
					setTimeout(uni.navigateBack, 1000);
				});
			}
		}
	});
}

/**
 * @param {'device_imgs' | 'cha_imgs'} key
 */
function handleDeleteImg(index, key) {
	uni.showModal({
		title: '提示',
		content: '确定删除图片吗？',
		confirmColor: '#377DFF',
		success(res) {
			if (res.confirm) {
				formFields.value[key].splice(index, 1);
			}
		}
	});
}

/**
 * @param {'device_imgs' | 'cha_imgs'} key
 */
function uploadImgsHandler(key) {
	uni.chooseImage({
		count: 9 - formFields.value[key].length,
		sourceType: ['camera'],
		success: (chooseImageRes) => {
			const tempFilePaths = chooseImageRes.tempFilePaths;
			for (const path of tempFilePaths) {
				uploadFile(path).then((res) => {
					formFields.value[key].push(res);
				});
			}
		}
	});
}

function onRadioChange(e, item) {
	const { value } = e.detail;
	item.checked = +value;
}
</script>

<style scoped lang="scss">
.scanCode {
	background: #fff;
	font-size: 28rpx;
}
.chassis_num {
	position: relative;
	&_del {
		position: absolute;
		right: 20rpx;
	}
}
.patrol-inspection {
	display: flow-root;
	.box {
		margin: 30rpx;
		border-radius: 10rpx;
		background-color: #ffffff;
		.title {
			height: 92rpx;
			display: flex;
			align-items: center;
			color: #333;
			font-size: 34rpx;
			font-weight: bold;
			padding-left: 30rpx;
			padding-right: 30rpx;
			position: relative;
			&::before {
				content: '';
				position: absolute;
				left: 0;
				width: 10rpx;
				height: 32rpx;
				border-radius: 4rpx;
				background-color: #4771f6;
			}
		}
		.form-box {
			padding: 0 30rpx 30rpx;
			.label {
				padding: 30rpx 0;
				color: #333;
				font-weight: 500;
			}
			.radio-group {
				display: flex;
				flex-wrap: wrap;
				.radio-label {
					font-size: 28rpx;
					padding-right: 60rpx;
					&:last-child {
						padding-right: 0;
					}
				}
			}
			.form-textarea {
				padding: 20rpx;
				border-radius: 8rpx;
				box-sizing: border-box;
				background-color: #f8f8f8;
				.textarea-box {
					height: 120rpx;
					font-size: 28rpx;
				}
				.grid-box {
					display: grid;
					grid-template-columns: repeat(4, 1fr);
					gap: 20rpx;
					.grid-item {
						height: 132rpx;
						border-radius: 10rpx;
						overflow: hidden;
						position: relative;
						.cover-image {
							width: 100%;
							height: 100%;
						}
						.icon-close {
							position: absolute;
							right: 10rpx;
							top: 10rpx;
							color: #fff;
							font-size: 20rpx;
							border-radius: 50%;
							padding: 10rpx;
							background-color: $red-color;
						}
					}
					@mixin addIcon {
						content: '';
						position: absolute;
						background-color: #b1b1b1;
					}
					.upload-box {
						background-color: #efefef;
						position: relative;
						&::before {
							width: 60rpx;
							height: 2rpx;
							@include addIcon();
						}
						&::after {
							width: 2rpx;
							height: 60rpx;
							@include addIcon();
						}
					}
				}
			}
		}
	}
	.border-top {
		border-top: 2rpx solid #efefef;
	}
	.btn-submit {
		margin: 60rpx 30rpx;
	}
}
</style>
<style>
page {
	background-color: #f8f8f8;
}
</style>
